<template>
	<div class="app-container">
		<el-breadcrumb separator="/" style="padding:10px;padding-bottom:0;">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item><a href="#/monitoringanalysis">监控分析</a></el-breadcrumb-item>
			<el-breadcrumb-item><a href="#/vedioanalysis">视频分析</a></el-breadcrumb-item>
		</el-breadcrumb>
		<el-form :model="ruleForm" ref="ruleForm" :inline="true" label-width="68px"
			style="padding: 20px;padding-bottom: 0;">
			<el-row :gutter="10">
				<el-col :span="6">
					<el-form-item label="司机名" prop="driverName" label-width="60px">
						<el-autocomplete class="inline-input" size="small" v-model="ruleForm.driverName"
							:fetch-suggestions="querySearch" placeholder="请输入司机名" @select="handleSelect" clearable
							@clear="setBlur()"></el-autocomplete>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="司机号" prop="driverNum" label-width="60px">
						<el-input v-model="ruleForm.driverNum" clearable size="small"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="车次" prop="trainNum" label-width="40px">
						<el-input v-model="ruleForm.trainNum" placeholder="请输入车次" clearable size="small"
							@keyup.enter.native="handleQuery" />
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="机车号" prop="cabNum" label-width="60px">
						<el-input v-model="ruleForm.cabNum" clearable size="small"></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-form-item style="display: flex;justify-content: flex-end;">
				<el-button type="primary" icon="el-icon-search" size="mini" @click="submitForm">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetForm('ruleForm')">重置</el-button>
			</el-form-item>
		</el-form>
		<el-row>
			<el-col :span="17">
				<el-table ref="pageTable" class="loading-area" :current-row-key="currentIndex"
					:highlight-current-row="true" @row-click="rowClickTabel" :row-class-name="tableRowClassName" border
					:data="dataList" stripe @cell-dblclick="celldblclick">
					<el-table-column type="index" width="50"></el-table-column>
					<el-table-column label="机车号" align="center" prop="cabNum" />
					<el-table-column label="车次" align="center" prop="trainNum" />
					<el-table-column label="司机号" align="center" prop="driverNum" />
					<el-table-column label="司机名" align="center" prop="driverName" />
					<el-table-column label="创建时间" width="180" align="center" prop="createTime">
						<template slot-scope="scope">
							{{ strainer(scope.row.createTime) }}
						</template>
					</el-table-column>
					<el-table-column label="日期" width="120" align="center" prop="date" />
					<el-table-column label="开始时间" width="180" align="center" prop="startTime" />
					<el-table-column label="结束时间" width="180" align="center" prop="endTime" />
					<el-table-column label="文件数" align="center" prop="fileNum" />
					<el-table-column label="文件容量(MB)" width="120" align="center" prop="size">
						<template slot-scope="scope">
							<span>{{ (scope.row.size / 1024).toFixed(2) }}</span>
						</template>
					</el-table-column>
					<el-table-column label="目录" align="center" prop="dir" width="650" class="hides" />
					<el-table-column label="idx名称" align="center" prop="fileName" width="280" class="hides" />
				</el-table>
			</el-col>
			<el-col :span="7" style="height:100%;">
				<div class="table_two">
					<div class="top">
						<el-table :data="tableDataLeft" @row-click="rowClick" border height="265" style="width: 100%">
							<el-table-column prop="name" width="180" label="相同名称分类">
							</el-table-column>
							<el-table-column prop="con" label="总次数">
							</el-table-column>
							<el-table-column prop="abnormalCount" label="违章次数">
							</el-table-column>
						</el-table>
					</div>
					<div class="bottom">
						<el-table :data="tableDataRight" border height="265" style="width: 100%"
							:row-class-name="tableRowClassName">
							<el-table-column prop="name" width="180" label="项目名称">
							</el-table-column>
							<el-table-column prop="code" label="类别/并发">
							</el-table-column>
							<el-table-column prop="time" width="160" label="起止时间">
							</el-table-column>
							<el-table-column prop="illegal" label="状态">
								<template slot-scope="scope">
									<!-- 0：违章，1：未处理，2：缺失，3：正常，4：记录 -->
									{{ scope.row.illegal=='4'?'记录':scope.row.illegal=='3'?'正常':scope.row.illegal=='2'?'缺失':scope.row.illegal=='1'?'未处理':'违章' }}
								</template>
							</el-table-column>
						</el-table>
					</div>
				</div>
			</el-col>
		</el-row>

		<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
			:current-page="queryParams.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="queryParams.pageSize"
			layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
		<div class="footer">
			<el-row class="footer_item">
				<el-col :span="24">
					<el-tabs type="border-card">
						<el-tab-pane label="必分析项点">
							<el-row>
								<el-col :span="4" v-for="(item,index) in phaseClassify" :key="index"
									class="flexBox_item"><span class="title">{{item.name}}</span><span class="btn"
										@click="getClick(item.phaseCountVoList)">正常</span></el-col>
							</el-row>
						</el-tab-pane>
						<el-tab-pane label="违章及自定义">
							<el-row>
								<el-col :span="4" v-for="(item,index) in illegalPhaseItems" :key="index"
									class="flexBox_item"><span class="title">{{item.name}}</span><span class="btn"
										@click="getClick(item.phaseCountVoList)">正常</span></el-col>
							</el-row>
						</el-tab-pane>
						<el-tab-pane label="全安控制项点">
							<el-row>
								<el-col :span="4" v-for="(item,index) in securePhaseItems" :key="index"
									class="flexBox_item"><span class="title">{{item.name}}</span><span class="btn"
										@click="getClick(item.phaseCountVoList)">正常</span></el-col>
							</el-row>
						</el-tab-pane>
						<el-tab-pane label="LKJ分析项点">
							<el-row>
								<el-col :span="4" v-for="(item,index) in lkjPhaseAnalysisItems" :key="index"
									class="flexBox_item"><span class="title">{{item.name}}</span><span class="btn"
										@click="getClick(item.phaseCountVoList)">正常</span></el-col>
							</el-row>
						</el-tab-pane>
						<el-tab-pane label="视频分析项点">
							<el-row>
								<el-col :span="4" v-for="(item,index) in idxPhaseAnalysisItems" :key="index"
									class="flexBox_item"><span class="title">{{item.name}}</span><span class="btn"
										@click="getClick(item.phaseCountVoList)">正常</span></el-col>
							</el-row>
						</el-tab-pane>
						<el-tab-pane label="标准化作业项点">
							<el-row>
								<el-col :span="4" v-for="(item,index) in handlePhaseItems" :key="index"
									class="flexBox_item"><span class="title">{{item.name}}</span><span class="btn"
										@click="getClick(item.phaseCountVoList)">正常</span></el-col>
							</el-row>
						</el-tab-pane>
					</el-tabs>
				</el-col>
				<!-- <el-col :span="7">
          <el-tabs type="border-card" >
            <el-tab-pane label="司机">
              <el-form :model="ruleForm"  ref="ruleForm1" label-width="100px" class="demo-ruleForm">

                <el-form-item label="司机号" prop="driverNum">
                  <el-input v-model="ruleForm.driverNum"></el-input>
                </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm1')">查询</el-button>
                    <el-button @click="resetForm('ruleForm1')">重置</el-button>
                  </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="机车">
              <el-form :model="ruleForm" ref="ruleForm2" label-width="100px" class="demo-ruleForm">
   
                  <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm2')">查询</el-button>
                    <el-button @click="resetForm('ruleForm2')">重置</el-button>
                  </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="车次">
              <el-form :model="ruleForm"  ref="ruleForm3" label-width="100px" class="demo-ruleForm">
                <el-form-item label="车次" prop="trainNum">
                  <el-input v-model="ruleForm.trainNum"></el-input>
                </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm3')">查询</el-button>
                    <el-button @click="resetForm('ruleForm3')">重置</el-button>
                  </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-col> -->
			</el-row>
		</div>
	</div>
</template>
<script>
	import axios from 'axios'
	export default {
		name: 'index',
		data() {
			return {
				baseUrl: '',
				lkjPhaseTypes: require('./lkjPhaseTypes.json'),
				lkjProcessPhases: require('./lkjPhases.json'),
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 总条数
				total: 0,
				// 表格数据
				dataList: [],
				// 弹出层标题
				title: '',
				// 是否显示弹出层
				open: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
				},
				id: '',
				columnInfos: [], // 所有列信息
				showAlwaysShowColumnInCheckbox: true,
				dynamicColumnSetting: true,
				columnVisibles: new Array(30).fill(true), //设置列可见性
				visibleIndexs: [], // 可见列的下标集合
				alwaysShowColumnIndexs: [], //总是显示的列的下标（不可隐藏的列）,列下标从 0 开始
				hidenColumnIndexs: [], //隐藏列的下标集合
				// 表单参数
				form: {},
				tableDate: [],
				textarea: '',
				tableDataLeft: [],
				tableDataRight: [],
				phaseClassify: [],
				lkjPhaseAnalysisItems: [], //LKJ分析项点
				idxPhaseAnalysisItems: [], //视频分析项点
				secureControlItems: [], //安全控制项点
				securePhaseItems: [], //安全控制项点集合
				illegalPhaseItems: [], //违章及自定义
				handlePhaseItems: [], //标准化作业项点
				phaseId: '',
				ruleForm: {
					driverName: '',
					driverNum: '',
					cabNum: '',
					trainNum: '',
				},
				valueList: [],
				restaurants: [],
				currentIndex: '',
				isrecord: false
			};
		},
		created() {
			this.id = this.$route.query.id ? this.$route.query.id : ''
			if (this.$route.query.id) {
				this.isrecord = true
			}
			this.init();
		},
		methods: {
			tableRowClassName({
				row,
				rowIndex
			}) {
				if (rowIndex === this.currentIndex) {
					return 'current-row';
				}
				return '';
			},
			getSiji() {
				let str = encodeURIComponent(this.ruleForm.driverName)
				axios.get(`/api/lkj/index/driverLike?driver=${str}`).then(res => {
					res.data.data.forEach(item => {
						item.value = item.name
					})
					this.restaurants = res.data.data
				})
			},
			createFilter(queryString) {
				return (restaurant) => {
					return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
				};
			},
			querySearch(queryString, cb) {
				var restaurants = this.restaurants;
				var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
				// // 调用 callback 返回建议列表的数据
				cb(results);
			},
			handleSelect(item) {
				console.log('getSiji', item);
				this.ruleForm.driverNum = item.jobNum
			},
			submitForm(formName) {
				this.queryParams.pageNum = 1
				this.getTable()
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
				this.queryParams.pageNum = 1
				this.getTable()
			},
			getvalue() {
				axios.get(`/api/ApiData/index?url=api/idx/phase/getListByRId&method=GET&recordId=${this.id}`).then(res => {
					this.valueList = res.data.data
					this.phaseClassify.forEach(item => {
						this.valueList.forEach(it => {
							if (item.name == it.name) {
								item.phaseCountVoList = it.phaseCountVoList
							}
						})
					})
					this.illegalPhaseItems = this.illegalPhaseItemsFuction() //违章及自定义
					this.lkjPhaseAnalysisItems = this.lkjPhaseAnalysisItemsFuction() //LKJ分析项点
					this.idxPhaseAnalysisItems = this.idxPhaseAnalysisItemsFuction() //视频分析项点
					this.securePhaseItems = this.securePhaseItemsFuction() //安全控制项点
					this.handlePhaseItems = this.handlePhaseItemsFuction()
					this.getPhaseCountFunction()
				})
			},
			getClick(item) {
				if (item.length > 0 && item[0].phaseId) {
					this.getListByRIdAndId(item[0].phaseId)
				} else {
					this.tableDataRight = []
				}
			},
			rowClickTabel(row, column, event) {
				console.log('row,column, event', row, column, event)
				this.id = row.recordId
				this.getAllConfigPhase();
			},
			celldblclick(row, column, cell, event) {
				this.$router.push(`/videoDetail?id=${row.id}&recordId=${row.recordId}`)
			},
			rowClick(row) {
				this.tableDataRight = []
				this.getListByRIdAndId(row.phaseId)
			},
			init() {
				this.getTable();
				this.getSiji();
				const items = this.lkjProcessPhases.filter((phase) => phase.secureControl === 1)
				this.secureControlItems = this.convertPhaseTypes(items, this.lkjPhaseTypes)
				this.getAllConfigPhase();


			},
			getNum() {
				axios.get(
						`/api/ApiData/index?url=api/idx/phase/getListByRIdAndId&method=GET&recordId=${this.id}&phaseId=0`)
					.then(res => {
						// axios.get(`${this.baseUrl}api/idx/phase/getListByRIdAndId/${this.id}/0`,{ params: {},jsonp: 'callback'}).then(res => {
						console.log('getNum', res)
						let arr = res.data.data
						let newArr = []
						arr.forEach(item => {
							if (item.illegal == 0) {
								newArr.push(item)
							}
						})
						console.log('newArr', newArr)
					})
			},
			getListByRIdAndId(value) {
				axios.get(
					`/api/ApiData/index?url=api/idx/phase/getListByRIdAndId&method=GET&recordId=${this.id}&phaseId=${value}`
				).then(res => {
					res.data.data.forEach(item => {
						item.time = item.startTime.split(' ')[1] + '-' + item.endTime.split(' ')[1]
					})
					this.tableDataRight = res.data.data
				})
			},
			getPhaseCountFunction() {
				axios.get(
					`/api/ApiData/index?url=api/lkj/index/getPhaseCount&method=GET&id=${this.phaseId}&recordId=${this.id}`
				).then(res => {
					this.tableDataLeft = res.data.data
					this.getListByRIdAndId(res.data.data[0].phaseId)
				})
			},
			convertPhaseTypes: function(list, lkjPhaseTypes) {
				// 获取所有的大类编号
				const typeList = list.map((item) => item.type)
				// 去重
				const typeSet = new Set(typeList)
				const types = [...typeSet]
				// 映射结果
				const typeItems = types.map((type) => {
					const typeObj = lkjPhaseTypes.find((phaseType) => phaseType.key === type)
					const items = list.filter((item) => item.type === type)
					const obj = items.reduce((result, item) => {
						return {
							illegal: item.illegal + result.illegal,
							normal: item.normal + result.normal,
							record: item.record + result.record
						}
					}, {
						illegal: 0,
						normal: 0,
						record: 0
					})
					return Object.assign({}, typeObj, {
						items
					}, obj)
				})
				return typeItems
			},
			getConfigPhase() {
				axios.get(`/api/ApiData/index?url=api/lkj/configPhase&method=GET&status=1`).then(res => {
					this.phaseClassify = res.data.data
					this.phaseId = res.data.data[0].id
					this.getvalue();
				})
			},
			getAllConfigPhase() {
				axios.get(`/api/ApiData/index?url=api/lkj/configPhase&method=GET`).then(res => {
					this.phaseAll = res.data.data
					this.getConfigPhase();
				})
			},
			// 按项点名称归类好的项点
			phaseClassifyFuncton() {
				// 获取项点名称，并去重
				const phaseNameSet = new Set(this.analysisPhases.records.map((phase) => phase.name))
				const phaseNames = [...phaseNameSet]
				const list = phaseNames.map((name) => {
					// 相同名称的项点集合
					const items = this.analysisPhases.records.filter((phase) => phase.name === name)
					// 违章次数
					const statistics = items.reduce((count, item) => {
						return Object.assign({}, count, {
							illegal: count.illegal + (item.illegal === 0 ? 1 : 0),
							code: item.code
						})
					}, {
						illegal: 0,
						code: ''
					})
					const data = {
						name: name,
						count: items.length,
						items: items,
						illegalCount: statistics.illegal || 0,
						code: statistics.code
					}
					return data
				})
				list.unshift({
					name: '全部',
					count: this.analysisPhases.records.length,
					items: this.analysisPhases.records,
					illegalCount: list.reduce((sum, item) => sum + item.illegalCount, 0),
					code: ''
				})
				return list
			},
			// 违章及自定义
			illegalPhaseItemsFuction() {
				const list = this.phaseClassify.filter((phase) => phase.illegalCount > 0 && phase.name !== '全部' && phase
					.type === 'LKJ')
				const index = list.findIndex((item) => item.name === '自定义项点')
				if (index < 0) {
					list.unshift({
						name: '自定义项点',
						count: 0,
						items: [],
						illegalCount: 0,
						code: ''
					})
				}
				return list
			},
			// LKJ分析项点
			lkjPhaseAnalysisItemsFuction() {
				const list = this.phaseClassify.filter((phase) => phase.type === 'LKJ')
				return list
			},
			// && phase.items && phase.items.length > 0
			// 视频分析项点
			idxPhaseAnalysisItemsFuction() {
				const list = this.phaseClassify.filter((phase) => phase.type === 'IDX')
				return list
			},
			// 标准化作业项点
			handlePhaseItemsFuction() {
				const list = this.phaseAll.filter((phase) => phase.type === 'H')
				const items = list.map((item) => {
					const phase = this.phaseClassify.find((p) => p.name === item.name)
					if (phase) {
						return phase
					}
					return {
						name: item.name,
						count: 0,
						items: [],
						illegalCount: 0,
						code: item.type
					}
				})
				return items
			},
			// 安全控制项点
			securePhaseItemsFuction() {
				const labels = this.secureControlItems.map((phase) => phase.value)
				const list = labels.map((label) => {
					const obj = this.phaseClassify.find((phase) => phase.name === label)
					if (!obj) {
						return {
							name: label
						}
					}
					return obj
				})
				return list
			},
			strainer(value, type) {
				const dt = new Date(value)
				// 返回年数的四位数方法
				const y = dt.getFullYear()
				// 月份从0开始，所有要加1，如果不足两位用es6字符串方法补0
				const m = (dt.getMonth() + 1 + '').padStart(2, '0')
				const d = (dt.getDate() + '').padStart(2, '0')

				const hh = (dt.getHours() + '').padStart(2, '0')
				const mm = (dt.getMinutes() + '').padStart(2, '0')
				const ss = (dt.getSeconds() + '').padStart(2, '0')
				if (type === 'yyyy-MM-dd') {
					return `${y}-${m}-${d}`
				} else if (type === 'hh:mm') {
					return `${hh}:${mm}`
				} else if (type === 'yyyy年MM月') {
					return `${y}年${m}月`
				} else {
					return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
				}
			},
			getTable() {
				let {
					pageNum,
					pageSize
				} = this.queryParams
				let {
					driverNum,
					cabNum,
					trainNum
				} = this.ruleForm
				let strings = ''
				if (this.isrecord) {
					strings =
						`/api/ApiData/index?url=api/idx/index/list&method=GET&pageNum=${pageNum}&pageSize=${pageSize}&recordId=${this.id}&driverNum=${driverNum}&cabNum=${cabNum}&trainNum=${trainNum}`
				} else {
					strings =
						`/api/ApiData/index?url=api/idx/index/list&method=GET&pageNum=${pageNum}&pageSize=${pageSize}&driverNum=${driverNum}&cabNum=${cabNum}&trainNum=${trainNum}`
				}
				axios.get(strings).then(res => {
					let item = res.data.data
					if (!this.id) {
						this.id = item.rows[0].recordId
					}
					this.dataList = item.rows
					this.total = item.total
					this.queryParams.pageNum = item.currentPage
					this.getNum()
				})
			},
			getLkjPhaseListByType() {
				const typesList = this.lkjPhaseTypes.map((type) => {
					const items = this.lkjProcessPhases.filter((phase) => phase.type === type.key)
					return Object.assign({}, type, {
						items
					})
				})
				return typesList
			},
			tableRowClassName({
				row,
				rowIndex
			}) {
				if (row.illegal === 0) {
					return 'warning-row';
				} else {
					return 'success-row';
				}
			},
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.queryParams.pageNum = 1
				this.queryParams.pageSize = val
				this.getTable()
			},
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.queryParams.pageNum = val
				this.getTable()
			},
			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
		},
	};
</script>
<style scoped>
	.el-table .warning-row {
		background: oldlace;
	}

	.el-table .success-row {
		background: #f0f9eb;
	}

	.el-pagination {
		text-align: center;
		margin-top: 10px;
	}

	.footer {
		border: 1px solid #ccc;
		margin-top: 10px;
	}

	.analysis_info {
		display: flex;
		padding: 10px;
	}

	.analysis_info span {
		margin-right: 20px;
		font-size: 15px;
		color: blue;
		font-weight: 700;
	}

	.footer_item {
		background: #d4dff3;
	}

	.footer_item .table_two {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.footer_item .table_two .top {
		height: 50%;
	}

	.footer_item .table_two .bottom {
		height: 50%;
	}

	.flexBox {
		display: flex;
		justify-content: space-between;
		flex-wrap: wrap;
	}

	.flexBox_item {
		display: flex;
		justify-content: space-between;
		margin: 5px 0;
		align-items: center;
		padding-left: 20px;
	}

	.flexBox_item .title {
		font-size: 12px;
		color: #000;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		flex: 1;
	}

	.flexBox_item .btn {
		background: #fff;
		font-size: 12px;
		color: #000;
		padding: 3px 10px;
		border-radius: 10px;
		border: 1px solid #ccc;
		width: 46px;
		box-sizing: border-box;
	}

	v-deep .el-tabs--border-card {
		height: 200px;
	}

	/deep/.el-tabs__content {
		background: #d4dff3;
	}

	.hides {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	/deep/.current-row {
		background: oldlace;
	}
</style>